import React, { Component } from 'react'
import axios from 'axios';
import "./App.css";
import moment from "moment";//js日期库

export default class App extends Component {
  componentDidMount(){
    this.getData(1);
  }
  getData(pno){
    const url="http://101.96.128.94:9999/mfresh/data/news_select.php?pageNum="+pno;
    axios.get(url).then((res)=>{
      console.log(res);
      this.data=res.data;
      //刷新页面
      this.setState({});
    })
  }
  showContent=()=>this.data.data.map((item,index)=>(
    <div key={index}>
      <span>{item.title}</span>
      <span>{this.converDate(item.pubTime)}</span>
    </div>
  ))
  // 日期转换：时间戳->年月日
  converDate(ts){
    //返回之中的时间戳是字符转格式，要求必须是数字
    const date=new Date(ts*1);
    return moment(date).format("yyyy-MM-DD");
  }
  showPages(){
    const pages=[];
    for(let i=1;i<=this.data.pageCount;i++){
      pages.push(
      <span 
        onClick={this.getData.bind(this,i)}
        className={i==this.data.pageNum?"cur":""} key={i}>{i}</span>)
    }
    return pages
  }
  showPrev(){
    if(this.data.pageNum>1){
      return(
        <span onClick={()=>this.getData(this.data.pageNum-1)}>上一页</span>
      );
    }else{
      return <span className="disable">上一页</span>
    }
  }
  showNext(){
    if(this.data.pageNum<this.data.pageCount){
      return(
        <span onClick={()=>this.getData(this.data.pageNum+1)}>下一页</span>
      );
    }else{
      return <span className="disable">下一页</span>
    }
  }
  render() {
    if(!this.data) return <div/>
    return (
      <div className="body">
        <div className="content">{this.showContent()}</div>
        <div className="pages">
          {this.showPrev()}
          {this.showPages()}
          {this.showNext()}
        </div>
      </div>
    )
  }
}
